#!/usr/bin/python
import re
import MySQLdb
from datetime import datetime
import settings

class SolarReader:


	def getHistory(self,rows, hours = 0):
		db = MySQLdb.connect(host=settings.DATABASE_HOST, user="root", db="solar")
		cursor = db.cursor()
		cursor.execute("select * from solar_data where time <TIMESTAMPADD(HOUR,0,NOW())order by time desc")
		db.close()
		return cursor.fetchmany(rows)


	

if __name__ == "__main__":
	reader = SolarReader()
	print "Content-Type: text/html\n\n"
	now = datetime.now()
	energy = reader.getEnergy()
	print "<html><title>Halem Solar Data (beta)</title><body>"
	print '<link rel="icon" href="favicon.ico" type="image/vnd.microsoft.icon">'
	print "<H1>Halem Solar Data (beta)</H1>"
	print "<pre>"
	print now.strftime("%I:%M%p %m-%d-%Y")
	print "Watts: %s" % energy[0]
	print "Max Watts Today: %s" % reader.getMaxWatts() 
	print "kWh Today: %s" % energy[1]
	print "kWh Lifetime: %s" % energy[2]
	print "</pre>"
	f = open("chart.html","r")
	print f.read()
	rows =  reader.getHistory(12)
	print "<H2>Last %d Readings</H2>" % len(rows)
	print "<table border=1>"
	print "<tr><td>Time</td><td>Watts</td><td>kWh Today</td><td>kWh Lifetime</td></tr>"
	for row in rows:
		print "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (row[0].strftime("%I:%M%p %m-%d-%Y"), row[1], row[2], row[3])
	print "</table>"
	print "</body></html>"
